package com.tanqidi.arcgisandroid.ui.layerConfig.subLayer.fieldConfig

import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.textfield.TextInputEditText
import com.jaredrummler.android.colorpicker.ColorPickerDialog
import com.jaredrummler.android.colorpicker.ColorShape
import com.tanqidi.arcgisandroid.R
import com.tanqidi.arcgisandroid.base.BaseRecyclerAdapter
import com.tanqidi.arcgisandroid.base.RecyclerViewHolder
import com.tanqidi.arcgisandroid.base.utils.showToast
import com.tanqidi.arcgisandroid.data.layerConfig.Field
import com.tanqidi.arcgisandroid.data.layerConfig.LayerConfig
import com.tanqidi.arcgisandroid.data.project.Project
import com.tanqidi.arcgisandroid.databinding.FragmentFieldConfigBinding
import com.tanqidi.arcgisandroid.ui.MainActivity
import com.tanqidi.arcgisandroid.ui.MainViewModel
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class FieldConfigFragment : Fragment() {

    private lateinit var binding: FragmentFieldConfigBinding
    private val fieldConfigViewModel by viewModels<FieldConfigViewModel>()
    private val mainViewModel by activityViewModels<MainViewModel>()
    private val args by navArgs<FieldConfigFragmentArgs>()
    //选择颜色的view
    private lateinit var colorView: View
    private var isBorderColor = false
    private lateinit var fieldTypeArrayAdapter: ArrayAdapter<String>
    private lateinit var showTypeArrayAdapter: ArrayAdapter<String>
    private val fieldTypeList = listOf(Field.INPUT_TYPE_STRING, Field.INPUT_TYPE_INT, Field.INPUT_TYPE_DOUBLE)
    private val showTypeList = listOf(Field.SHOW_TYPE_INPUT, Field.SHOW_TYPE_SELECT)

    //从本地读取出来的layer对象
    private lateinit var layer: LayerConfig
    private lateinit var project: Project
    private lateinit var fieldAdapter: FieldAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = FragmentFieldConfigBinding.inflate(layoutInflater)
        fieldTypeArrayAdapter = ArrayAdapter(requireContext(), R.layout.cat_exposed_dropdown_popup_item, fieldTypeList.toTypedArray())
        showTypeArrayAdapter = ArrayAdapter(requireContext(), R.layout.cat_exposed_dropdown_popup_item, showTypeList.toTypedArray())
        //读取出来project
        project = fieldConfigViewModel.getProjectByName(args.projectName)
        //project有了然后再从project中拿到layer对象
        layer = project.layers.filter { it.name == args.layerName }[0]
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        initTopBar()
        initViewEvent()
        initLiveData()
        initData()
        return binding.root
    }

    private fun initData() {
        val recyclerView = binding.recyclerView
        val layoutManager = object : LinearLayoutManager(requireContext()) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        recyclerView.layoutManager = layoutManager
        fieldAdapter = FieldAdapter(requireContext(), layer.fields)
        recyclerView.adapter = fieldAdapter
    }

    private fun initLiveData() {
        mainViewModel.colorLiveData.observe(viewLifecycleOwner) {
            //转16进制，保存进layer
            colorView.setBackgroundColor(it)
            if(isBorderColor){
                layer.borderColor = it
            } else {
                layer.color = it
            }
        }
    }

    private fun initViewEvent() {
        binding.featureLayerUrl.setText(layer.featureLayerUrl)

        val toTypedArray = layer.fields.map { it.alias }
        val fieldListAdapter = ArrayAdapter(requireContext(), R.layout.cat_exposed_dropdown_popup_item, toTypedArray)

        binding.labelTextInputLayout.setEndIconOnClickListener {
            binding.label.text = null
            layer.label = "ObjectId"
        }
        binding.label.apply {
            layer.fields.filter { it.field == layer.label }.let {
                if(it.isNotEmpty()){
                    setText(it[0].alias)
                }
            }

            setAdapter(fieldListAdapter)
            setOnItemClickListener { parent, view, position, id ->
                val item = toTypedArray[position]
                val field = layer.fields.filter { it.alias == item }[0]
                layer.label = field.field
            }
        }


        binding.iconResourceTextInputLayout.setEndIconOnClickListener {
            binding.label.text = null
            layer.icon = "ObjectId"
        }
        binding.iconResource.apply {
            layer.fields.filter { it.field == layer.icon }.let {
                if(it.isNotEmpty()){
                    setText(it[0].alias)
                }
            }
            setAdapter(fieldListAdapter)
            setOnItemClickListener { parent, view, position, id ->
                val item = toTypedArray[position]
                val field = layer.fields.filter { it.alias == item }[0]
                layer.icon = field.field
            }
        }

        binding.width.apply {
            setText(layer.width.toString())
            addTextChangedListener {
                val content = it.toString().trim()
                if(!TextUtils.isEmpty(content)){
                    layer.width = content.toInt()
                } else {
                    layer.width = 1
                }
            }
        }
        binding.borderColor.apply {
            setBackgroundColor(layer.borderColor)
            setOnClickListener {
                colorView = it
                isBorderColor = true
                ColorPickerDialog.newBuilder()
                    .setDialogType(ColorPickerDialog.TYPE_PRESETS)
                    .setAllowPresets(true)
                    .setColorShape(ColorShape.SQUARE)
                    .setDialogId(MainActivity.DIALOG_COLOR_ID)
                    .setColor(layer.borderColor)
                    .setAllowCustom(true)
                    .setShowAlphaSlider(true)
                    .setShowColorShades(true)
                    .show(requireActivity())
            }
        }
        binding.contentColor.apply {
            setBackgroundColor(layer.color)
            setOnClickListener {
                colorView = it
                isBorderColor = false
                ColorPickerDialog.newBuilder()
                    .setDialogType(ColorPickerDialog.TYPE_PRESETS)
                    .setAllowPresets(true)
                    .setColorShape(ColorShape.SQUARE)
                    .setDialogId(MainActivity.DIALOG_COLOR_ID)
                    .setColor(layer.color)
                    .setAllowCustom(true)
                    .setShowAlphaSlider(true)
                    .setShowColorShades(true)
                    .show(requireActivity())
            }
        }
    }

    private fun initTopBar() {
        binding.topAppBar.apply {
            setNavigationOnClickListener {
                findNavController().navigateUp()
            }
            setOnMenuItemClickListener {
                when(it.itemId) {
                    R.id.save -> {
                        save()
                        showToast("保存成功")
                    }
                    R.id.add ->{
                        fieldAdapter.add(Field())
                    }
                }
                false
            }
        }

    }

    override fun onDestroyView() {
        super.onDestroyView()
        save()
    }

    private fun save(){
        //在返回页面的时候，重新保存project到本地
        layer.fields = fieldAdapter.data as ArrayList<Field>
        fieldConfigViewModel.saveProject(project)
    }

    private inner class FieldAdapter(context: Context, list: List<Field>) : BaseRecyclerAdapter<Field>(context, list) {
        override fun getItemLayoutId(viewType: Int): Int {
            return R.layout.item_field
        }

        override fun bindData(holder: RecyclerViewHolder, position: Int, item: Field) {
            holder.apply {
                (getView(R.id.alias) as TextInputEditText).apply {
                    setText(item.alias)
                    addTextChangedListener {
                        item.alias = it.toString().trim()
                    }
                }
                (getView(R.id.field) as TextInputEditText).apply {
                    setText(item.field)
                    addTextChangedListener {
                        item.field = it.toString().trim()
                    }
                }
                (getView(R.id.defaultValue) as TextInputEditText).apply {
                    setText(item.defaultValue)
                    addTextChangedListener {
                        item.defaultValue = it.toString().trim()
                    }
                }
                (getView(R.id.type) as AutoCompleteTextView).apply {
                    setText(item.type, false)
                    setAdapter(fieldTypeArrayAdapter)
                    setOnItemClickListener { parent, view, position, id ->
                        item.type = fieldTypeList[position]
                    }
                }
                (getView(R.id.showType) as AutoCompleteTextView).apply {
                    setText(item.showType, false)
                    setAdapter(showTypeArrayAdapter)
                    setOnItemClickListener { parent, view, position, id ->
                        item.showType = showTypeList[position]
                    }
                }
                getView(R.id.delete).setOnClickListener {
                    MaterialAlertDialogBuilder(requireContext())
                        .setTitle("提示")
                        .setMessage("确定删除该属性吗?")
                        .setPositiveButton("确定") { dialog, which ->
                            layer.fields.remove(item)
                            remove(absoluteAdapterPosition)
                        }.show().findViewById<TextView>(android.R.id.message)?.setTextColor(requireContext().resources.getColor(R.color.app_color_theme_1))
                }
            }
        }
    }
}